#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //创建3行
    ui->tableWidget->insertRow(0);
    ui->tableWidget->insertRow(1);
    ui->tableWidget->insertRow(2);
    //创建3列
    ui->tableWidget->insertColumn(0);
    ui->tableWidget->insertColumn(1);
    ui->tableWidget->insertColumn(2);
    //设置列名（设置水平方向表头）
    ui->tableWidget->setHorizontalHeaderItem(0, new QTableWidgetItem("姓名"));
    ui->tableWidget->setHorizontalHeaderItem(1, new QTableWidgetItem("学号"));
    ui->tableWidget->setHorizontalHeaderItem(2, new QTableWidgetItem("班级"));
    //添加数据
    ui->tableWidget->setItem(0, 0, new QTableWidgetItem("小明"));
    ui->tableWidget->setItem(0, 1, new QTableWidgetItem("01"));
    ui->tableWidget->setItem(0, 2, new QTableWidgetItem("五班"));

    ui->tableWidget->setItem(1, 0, new QTableWidgetItem("小强"));
    ui->tableWidget->setItem(1, 1, new QTableWidgetItem("02"));
    ui->tableWidget->setItem(1, 2, new QTableWidgetItem("五班"));

    ui->tableWidget->setItem(2, 0, new QTableWidgetItem("小红"));
    ui->tableWidget->setItem(2, 1, new QTableWidgetItem("03"));
    ui->tableWidget->setItem(2, 2, new QTableWidgetItem("五班"));
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_insertRow_clicked()
{
    //需要知道当前一共多少行
    int rowcount = ui->tableWidget->rowCount();

    //在最后一行之后新增一行
    ui->tableWidget->insertRow(rowcount);
    //注意此处的参数是"下标"，表示新增之后的这一行是第几行
}

void Widget::on_pushButton_takeRow_clicked()
{
    int row = ui->tableWidget->currentRow();
    ui->tableWidget->removeRow(row);
}

void Widget::on_pushButton_insertColumn_clicked()
{
    //先获取列数
    int columnCount = ui->tableWidget->columnCount();
    ui->tableWidget->insertColumn(columnCount);
    //设置列名
    const QString& text = ui->lineEdit->text();
    ui->tableWidget->setHorizontalHeaderItem(columnCount, new QTableWidgetItem(text));
}

void Widget::on_pushButton_deleteColumn_clicked()
{
    int curcol = ui->tableWidget->currentColumn();
    ui->tableWidget->removeColumn(curcol);
}
